<template>
  <md-popup v-model="show" position="bottom">
    <md-popup-title-bar only-close :title="$t('nft.sell') + form.name" title-align="left" @cancel="show = false" />
    <div style="background: #fff; padding: 20px">
      <md-input-item v-model="form.price" type="money" :placeholder="$t('nft.sell_describe')" is-highlight>
        <template #right>
          HWD
        </template>
      </md-input-item>
      <div style="padding-top: 20px">
        <md-button type="primary" :loading="loading" @click="action" round>{{ $t('confirm') }}</md-button>
      </div>
    </div>
  </md-popup>
  <Confirm ref="confirm" />
</template>

<script setup>
import { ref, defineExpose } from 'vue'
import { toast } from '@/style'
import { t } from '@/lang'
import { packager, random } from '@/web3'
import { push } from '@/api/market'
import Nav from '@/components/nav.vue'
import Confirm from '@/components/confirm.vue'

const emit = defineEmits(['confirm'])

const confirm = ref(null)
const show = ref(false)
const loading = ref(false)
const form = ref({
  type: 'sell',
  price: '',
  area_level: 0,
  area_id: 0,
  name: ''
})

const open = (data) => {
  show.value = true
  form.value.area_id = data.id
  form.value.area_level = data.level
  form.value.name = data.name
  form.value.price = ''
}

const action = () => {
  confirm.value.open([form.value.name, 'NFT'], 'Hello World', 'nft_gas_description', async() => {
    // 合并数据加入随机符
    const data = Object.assign({random: random()}, form.value)
    // 打包数据
    const pack = await packager(data)
    loading.value = true
    push(pack).then(res => {
      toast(t('ok'))
      show.value = false
      emit('confirm')
    }).catch(err => {
      toast(err.message)
    }).finally(() => {
      loading.value = false
    })
  })
}

defineExpose({ open })

</script>